<?php

namespace app\admin\model;

use app\admin\model\user\UserLevel;
use think\Model;
use traits\model\SoftDelete;


class CardOrder extends Model
{

    
    use SoftDelete;
    

    // 表名
    protected $name = 'card_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'pay_time_text'
    ];
    

    



    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['pay_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function add($param)
    {
        $card = UserLevel::get($param['level_id']);

        $model = new CardOrder();

        $data = [
            'user_id'        => $param['user_id'],
            'pay_price'          => $card['price'],
            'order_no'       => $this->order_no(),
            'level_id'      =>  $param['level_id'],
        ];

        $wechatUser = User::get($param['user_id']);
        $model->data($data);
        $res =  $model->save();

        if ($res){
            $request = request();
            $notifyurl =  $request->root(true)."/api/block/cardnotifyx";

            $pay = \addons\epay\library\Service::submitOrder($data['pay_price'],$data['order_no'],'wechat','会员卡',$notifyurl,'','miniapp',$wechatUser['wechat_open_id']);
            return $pay;
        } else {
            return false;
        }
    }

    public function order_no(){
        $order_no = null;
        while (true) {
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $exist_order_no = CardOrder::get(['order_no' => $order_no]);
            if (!$exist_order_no) {
                break;
            }
        }
        return $order_no;
    }
}
